package com.zx._02_thread.线程池;

import com.zx.common.util.ThreadUtil;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class 线程池核心线程和队列变化 {

    @Test
    public void test1() {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,               // 核心5
                10,                         // 最大10
                5L, TimeUnit.SECONDS,       // 线程存活5S
                new LinkedBlockingQueue<Runnable>(10));//容量10

        // 提交11个任务，让线程池打满
        for (int i = 0; i < 100; i++) {
            final int idx = i + 1;

            pool.execute(() -> {
                log.info(">>>>>{}", idx);
                ThreadUtil.sleep(10L);
            });

            ThreadUtil.sleepMill(100L);

            log.info("核心线程数量={}, 已提交线程数量={}, 正在运行线程数量={}, 队列={}",
                    pool.getCorePoolSize(),
                    pool.getPoolSize(),
                    pool.getActiveCount(),
                    pool.getQueue().size()
            );
        }
    }


    @Test
    public void test2() {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,               // 核心5
                10,                         // 最大10
                5L, TimeUnit.SECONDS,       // 线程存活5S
                new LinkedBlockingQueue<Runnable>(10));//容量10

        for (int i = 0; i < 100; i++) {
            final int idx = i + 1;
            pool.execute(() -> {
                log.info(">>>>>{}", idx);
            });
            ThreadUtil.sleepMill(10L);
        }
    }

    @Test
    public void test3() {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,               // 核心5
                10,                         // 最大10
                5L, TimeUnit.SECONDS,       // 线程存活5S
                new SynchronousQueue<>());  // 同步队列

        for (int i = 0; i < 20; i++) {
            final int idx = i + 1;

            pool.execute(() -> {
                log.info(">>>>>{}", idx);
                ThreadUtil.sleep(5L);
            });

            log.info("提交任务={}", idx);
            ThreadUtil.sleepMill(100L);

        }
    }
}
